import xml.dom.minidom

class Config:
    def __init__(self, xml = "settings.xml"):
        self.xml = xml
        self.read()
        self.set_default()
        self.get_theme_values("default")
        self.get_theme_values(self.selected_theme)

    def set_default(self):
        '''
        generate the default values for the settings
        '''
        self.background = \
            self.foreground = \
            self.moon_path = \
            self.font_name = None
        self.font_size = \
            self.info = 0
        self.font_color = "#000000"
        self.info_pos = \
            self.moon_pos = (0, 0)

    def get_theme_by_name(self, name):
        '''
        returns an XML node coresponding to the theme with
        the supplied name
        '''
        for i in self.themes:
            if i.getAttribute("name") == name :
                return i

    def get_theme_values(self, theme):
        '''
        update the values the supplied theme has
        '''
        th = self.get_theme_by_name(theme)

        def get_attr(tag, attr, old_value = None):
            try:
                if th.getElementsByTagName(tag)[0].hasAttribute(attr):
                    return th.getElementsByTagName(tag)[0].getAttribute(attr)
                else:
                    return old_value
            except:
                return old_value

        self.background = get_attr("background", "image", self.background)
        self.foreground = get_attr("foreground", "image", self.foreground)
        self.moon_path = get_attr("moon", "images", self.moon_path)
        px = int(get_attr("moon", "pos_x", self.moon_pos[0]))
        py = int(get_attr("moon", "pos_y", self.moon_pos[1]))
        self.moon_pos = (px, py)
        self.font_name = get_attr("font", "path", self.font_name)
        self.font_size = int(get_attr("font", "size", self.font_size))
        c = get_attr("font", "color")
        if c != None:
            self.font_color = ( int(c[1:3], 16),
                                int(c[3:5], 16),
                                int(c[5:7], 16))
        self.info = int(get_attr("info", "enabled", self.info))
        px = int(get_attr("info", "pos_x", self.info_pos[0]))
        py = int(get_attr("info", "pos_y", self.info_pos[1]))
        self.info_pos = (px, py)
        

    def read(self):
        '''
        opens the document for reading
        and reads the default theme
        '''
        doc = xml.dom.minidom.parse(self.xml).childNodes[0]
        self.themes = doc.getElementsByTagName("themes")[0].getElementsByTagName("theme")
        self.selected_theme = doc.getElementsByTagName("this")[0].getAttribute("theme")
